package lotus.blog.lotusblog.config;

import lotus.blog.lotusblog.pojo.User;
import lotus.blog.lotusblog.utils.JwtToken;
import lotus.blog.lotusblog.utils.JwtUtil;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class LotusBlogRealm extends AuthorizingRealm {
    @Autowired
    JwtUtil jwtUtil;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();  //JwtToken中重写了这个方法了
        String username = jwtUtil.getUserClaim(token);   // 获得username

        if(jwtUtil.isExpire(token)){
            throw new ExpiredCredentialsException();
        }else if(username == null){
            throw new UnknownAccountException();
        }else if (!jwtUtil.verifyToken(token,username)){
            throw new ShiroException("无效token");
        }
        //用户不存在（这个在登录时不会进入，只有在token校验时才有可能进入）
        //根据用户名，查询数据库获取到正确的用户信息
        User user = new User();
        user.setUsername("lotus");
        user.setPassword("123456");
        //用户不存在（这个在登录时不会进入，只有在token校验时才有可能进入）
        if(user == null)
            throw new UnknownAccountException();
        return new SimpleAuthenticationInfo(user, token, getName());
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("认证");

        return null;
    }
}
